<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #box{width: 100px;height:100px;background: red;position: absolute;left:0;top:0;}
    </style>
</head>
<body>
<div id="box"></div>
<script>
    let obox = document.getElementById("box");

    // 按下
    obox.onmousedown = function (eve) {
        // 获取按下的事件对象，用来获取按下的一瞬间相对于当前元素的坐标
        let downE = eve || window.event;
        document.onmousemove = function (eve) {
            let moveE = eve || window.event;

            // 计算位置：移动时相对于页面的坐标 - 按下时相对于当前元素的坐标
            let l = moveE.pageX - downE.offsetX;
            let t = moveE.pageY - downE.offsetY;
            // 边界限定
            if (l < 0) l = 0;
            if (t < 0) t = 0;
            if (l > document.documentElement.clientWidth - obox.offsetWidth) {
                l = document.documentElement.clientWidth - obox.offsetWidth
            }
            if (t > document.documentElement.clientHeight - obox.offsetHeight) {
                t = document.documentElement.clientHeight - obox.offsetHeight;
            }

            // 设置给元素
            obox.style.left = l + "px";
            obox.style.top = t + "px";
        }
        // 抬起
        document.onmouseup = function () {
            // 清除移动和抬起
            document.onmousemove = null;
            document.onmouseup = null;
            return false;
        }
    }
</script>
</body>
</html>